package com.infoland.afanmall.base.view.webview;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.vondear.rxtools.RxBarTool;
import com.vondear.rxtools.RxTool;
import com.vondear.rxtools.view.RxTextAutoZoom;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author 王永吉
 * @date 2018/8/6 14:06
 */


public class WebViewActivity extends AppCompatActivity {
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.web_back)
    ImageView webBack;
    @BindView(R.id.web_progress)
    ProgressBar webProgress;
    @BindView(R.id.web_title_text)
    TextView webTitleText;
    @BindView(R.id.web_title)
    LinearLayout webTitle;
    //
    WebSettings webSettings;
    String title = "";
    private String webPath = "http://ptp.ccbz.org.cn/?traceability_code=2018042415045239016384&onOff=0";

    private int getLayout() {
        return R.layout.webview;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        ButterKnife.bind(this);
        StatusBarKit.immersive(this, webTitle);
        try {
            webPath = getIntent().getExtras().getString("url");
            ToolsKit.setText(webTitleText, getIntent().getExtras().getString("title"));
            initData();
        } catch (Exception e) {
            finish();
            ToolsKit.goCloseDh(this);
            ToastUtils.showShort("异常操作");
        }
    }

    private void initData() {
        webBack.setOnClickListener(view -> {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
                ToolsKit.goCloseDh(this);
            }
        });
        webProgress.setMax(100);
        addSettings();
        webView.setWebChromeClient(new WebChromeClient() {

            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                LogKit.E("webviwe ---->   ", "  " + title);
                if (title.length() <= 8) {
                    webTitleText.setText(title);
                }
            }

            public void onProgressChanged(WebView view, int newProgress) {
                webProgress.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
                LogKit.E("webviwe onProgressChanged---->   ", "  " + newProgress);


            }
        });

        webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!webView.getSettings().getLoadsImagesAutomatically()) {
                    webView.getSettings().setLoadsImagesAutomatically(true);
                }
                LogKit.E("onPageFinished ---->   ", "  onPageFinished");
                webProgress.setVisibility(View.GONE);
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                webProgress.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
                LogKit.E("onPageStarted ---->   ", "  onPageStarted");


            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogKit.E("url ---->   ", "    " + url);
                LogKit.E("view ---->   ", "  " + view);

                if (!url.startsWith("http:") && !url.startsWith("https:")) {
                    try {
                        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception var4) {
                        var4.printStackTrace();
                    }
                    return true;
                } else {
                    view.loadUrl(url);
                    return false;
                }
            }
        });
        webView.setDownloadListener(
                (paramAnonymousString1, paramAnonymousString2, paramAnonymousString3,
                 paramAnonymousString4, paramAnonymousLong) -> {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.setData(Uri.parse(paramAnonymousString1));
                    startActivity(intent);
                });
        LogKit.E("164 ---->   ", "164");
        webView.loadUrl(webPath);
        LogKit.E("帮助类完整连接 ---->   ", "  " + webPath);
    }

    private void addSettings() {
        webSettings = webView.getSettings();
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }
        if (Build.VERSION.SDK_INT >= 11) {
            webView.setLayerType(1, null);
        }
        webView.setLayerType(2, null); //硬件加速

        //设置WebView是否允许执行JavaScript脚本，默认false，不允许。
        webSettings.setJavaScriptEnabled(true);
        //WebView是否支持使用屏幕上的缩放控件和手势进行缩放，默认值true
        webSettings.setSupportZoom(false);
        //是否使用内置的缩放机制。内置的缩放机制包括屏幕上的缩放控件（浮于WebView内容之上）和缩放手势的运用。
        webSettings.setBuiltInZoomControls(false);
        //使用内置的缩放机制时是否展示缩放控件
        webSettings.setDisplayZoomControls(false);
        //WebView是否支持HTML的“viewport”标签或者使用wide viewport。
//        webSettings.setUseWideViewPort(true);
        //设置布局，会引起WebView的重新布局（relayout）,默认值NARROW_COLUMNS
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //是否允许WebView度超出以概览的方式载入页面，默认false。即缩小内容以适应屏幕宽度
//        webSettings.setLoadWithOverviewMode(true);
        //DOM存储API是否可用，默认false。
//        webSettings.setDomStorageEnabled(true);
    }

    @Override
    public void onBackPressed() {
        if (RxTool.isFastClick(400)) {
            finish();
            ToolsKit.goCloseDh(this);
        } else {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
                ToolsKit.goCloseDh(this);
            }
        }


    }
}

